#include "debug.hpp"
#include "decode.hpp"
#include "net/http_client.hpp"
#include "net/io_context.hpp"
#include <fmt/format.h>
#include <fstream>
#include <string_view>

void client(std::string license_plate) {
    io_context ctx;
    auto client = http_client::make();
    // 打开文件，转换为base64编码
    std::ifstream file(license_plate, std::ios::binary | std::ios::ate);
    if (!file) {
        throw std::runtime_error("Could not open file");
    }
    // 获取文件大小
    std::streamsize fileSize = file.tellg();
    file.seekg(0, std::ios::beg);
    // 创建一个字符串来存储文件内容
    std::string fileContent(fileSize, 0);
    // 读取文件内容到字符串
    if (!file.read(fileContent.data(), fileSize)) {
        throw std::runtime_error("Could not read file");
    }
    auto base64 = Base64::encode(fileContent);
    client->do_request({"GET",
                        "http://localhost:8080/api/license_plate",
                        {std::string(base64.begin(), base64.end())}},
                       [client](expected<int> ret,
                                http_client::http_response const &response) {
                           ret.expect("http://localhost:8080/api/license_plate");
                           fmt::println("{}", response.body);
                       });

    ctx.join();
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fmt::println("Usage: {} <license_plate>", argv[0]);
        return 1;
    }
    try {
        client(argv[1]);
    } catch (std::system_error const &e) {
        fmt::println("{} ({}/{})", e.what(), e.code().category().name(),
                     e.code().value());
    }
    return 0;
}